from django.shortcuts import render, get_object_or_404, redirect
# from django.views.generic import View
from blog.models import Article
# from comments.models import Comment
from comments.forms import CommentForm


# Create your views here.
def article_comment(request, pk):

    article = get_object_or_404(Article, pk=pk)

    if request.method == 'POST':  # 如果提交数据
        form = CommentForm(request.POST)
        if form.is_valid():  # 若表单数据合法
            comment = form.save(commit=False)  # 使用表单数据生成Comment实例，但是不提交
            comment.article = article  # 绑定评论到当前文章
            comment.save()  # 保存模型数据
            # 评论提交后回到该文章
            return redirect(article)
        else:
            comment_list = article.comment_set.all()
            context = {
                'article': article,
                'form': form,
                'comment_list': comment_list}
            return render(request, 'detail.html', context=context)

    return redirect(article)
